import 'package:flutter/material.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/models/goods/goods_obj.dart';
import 'package:xws/res/icons.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/utils/data_util.dart';
import 'package:xws/utils/dio_utils/request/goods_req.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/utils/tools_util.dart';
import 'package:xws/widgets/action_icon.dart';
import 'package:xws/widgets/app_btn.dart';
import 'package:xws/widgets/app_img.dart';
import 'package:xws/widgets/app_list_tile.dart';
import 'package:xws/widgets/goods_config/goods_detail/detail_page.dart';

/// 好友发布项
class FriendItem extends StatefulWidget {
  const FriendItem({Key? key, required this.index, required this.goodsObj}) : super(key: key);

  @override
  _FriendItemState createState() => _FriendItemState();

  final int index;

  final GoodsObj goodsObj;
}

class _FriendItemState extends State<FriendItem> with SafeState<FriendItem> {
  final double _imageSize = (sw - 76) / 3;

  GoodsObj get _g => widget.goodsObj;

  Future<void> _viewImages(List<String> imgs, String tag, int init) async {
    await assetsViewer(context, imgs, heroTag: tag, initIndex: init);
  }

  @override
  Widget build(BuildContext context) {
    return AppBtn.noPadding(
      onTap: () => push(
          context,
          DetailPage(
            index: widget.index,
            goods: _g,
            refresh: () {
              safeSetState(() {});
            },
          )),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(14).copyWith(bottom: 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                _buildUser,
                const SizedBox(height: 10),
                _buildText,
                const SizedBox(height: 10),
                _buildImgs,
                const SizedBox(height: 10),
                _buildLabels,
              ],
            ),
          ),
          const SizedBox(height: 10),
          _buildActions,
        ],
      ),
      color: white(context),
      radius: 10,
    );
  }

  Widget get _buildUser {
    return AppListTile(
      leading: Padding(
        padding: const EdgeInsets.only(right: 10),
        child: AppImg.fitCover(
          url: _g.user.avatarUrl,
          width: 36,
          height: 36,
          radius: 20,
        ),
      ),
      titleText: _g.user.nickName,
      subtitleText: getGoodsPubDate(_g.createdAt),
      trailing: AppBtn.center(
        onTap: () => shareGoods(_g),
        width: 36,
        height: 36,
        padding: EdgeInsets.zero,
        child: Icon(IR.share, size: 16, color: black(context).withOpacity(0.6)),
        color: Colors.transparent,
      ),
    );
  }

  Widget get _buildText {
    return Stack(
      alignment: Alignment.bottomRight,
      children: <Widget>[
        Align(
          alignment: Alignment.centerLeft,
          child: Text(
            _g.description,
            maxLines: 4,
            style: TextStyle(
              color: black(context),
              fontSize: 15.4,
              height: 1.6,
              letterSpacing: 0.7,
            ),
          ),
        ),
        if (_g.description.length > 20)
          Container(
            padding: const EdgeInsets.only(left: 10),
            color: white(context),
            child: Text(
              '查看更多',
              style: TextStyle(
                color: theme(context),
                fontSize: 15.4,
                height: 1.6,
                letterSpacing: 0.7,
              ),
            ),
          ),
      ],
    );
  }

  Widget get _buildImgs {
    final List<String> imgs = _g.photoUrlList;

    final int max = imgs.length > 3 ? 3 : imgs.length;

    return SizedBox(
      height: _imageSize,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Wrap(
          spacing: 4,
          runSpacing: 4,
          children: List<Widget>.generate(max, (int index) {
            final String tag = homeHeroTag.replaceFirst('{item}', widget.index.toString() + '_');

            return GestureDetector(
              onTap: () => _viewImages(imgs, tag, index),
              child: AppImg.fitCover(
                heroTag: tag + index.toString(),
                url: imgs[index],
                width: _imageSize,
                height: _imageSize,
              ),
            );
          }),
        ),
      ),
    );
  }

  Widget get _buildLabels {
    return Row(
      children: <Widget>[
        _buildLabel(getQualityValue(_g.age), theme(context), Icons.new_releases_rounded),
        _buildLabel(_g.city + ' ' + _g.region, Colors.blueGrey, Icons.location_city_rounded),
        _buildLabel(_g.distance, Colors.blueGrey, Icons.pin_drop_rounded),
      ],
    );
  }

  Widget _buildLabel(String content, Color color, IconData icon) {
    return Container(
      child: Row(
        children: <Widget>[
          Icon(icon, size: 18, color: color),
          const SizedBox(width: 4),
          Text(
            content,
            style: TextStyle(
              color: black(context).withOpacity(0.6),
              fontSize: 12,
            ),
          ),
        ],
      ),
      padding: const EdgeInsets.all(3).copyWith(right: 6),
      margin: const EdgeInsets.only(right: 6),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: black(context).withOpacity(0.06),
        borderRadius: BorderRadius.circular(3),
      ),
    );
  }

  Widget get _buildActions {
    return SizedBox(
      height: 50,
      child: Row(
        children: <Widget>[
          _buildActionItem(
            IR.un_like,
            IR.like,
            _g.likeCount.toString(),
            _g.likeFlag,
            onTap: () {
              _g.likeFlag ? _g.likeCount-- : _g.likeCount++;
              _g.likeFlag = !_g.likeFlag;

              safeSetState(() {});

              likeGoods(_g.id);
            },
          ),
          _buildActionItem(
            IR.comment,
            IR.comment,
            _g.commentCount.toString(),
            false,
            onTap: () => push(
              context,
              DetailPage(
                index: widget.index,
                goods: _g,
                autoOpenComment: true,
                refresh: () {
                  safeSetState(() {});
                },
              ),
            ),
          ),
          _buildActionItem(
            IR.un_star,
            IR.star,
            _g.favoriteCount.toString(),
            _g.favoriteFlag,
            onTap: () {
              _g.favoriteFlag ? _g.favoriteCount-- : _g.favoriteCount++;
              _g.favoriteFlag = !_g.favoriteFlag;

              safeSetState(() {});

              collectGoods(_g.id, !_g.favoriteFlag);
            },
          ),
        ],
      ),
    );
  }

  Widget _buildActionItem(
    IconData icon,
    IconData actionIcon,
    String content,
    bool isSelect, {
    Function()? onTap,
    double? iconSize,
  }) {
    return Expanded(
      child: ActionIcon(
        icon: icon,
        actionIcon: actionIcon,
        isSelect: isSelect,
        content: content,
        onTap: onTap,
        iconSize: iconSize,
      ),
    );
  }
}
